package com.controller;

import com.domain.Good;
import com.domain.User;
import com.service.IGoodService;
import com.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/user")
@SessionAttributes("uid")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IGoodService goodService;

    @RequestMapping("/userLogin")
    public String userLogin(User user, Model model){
        boolean r=userService.findUserById(user);
        if (r==true){
            model.addAttribute("uid",user.getUid());
            return "redirect:/user/goodList";
        }else{
            return "error";
        }
    }

    @RequestMapping("/goodList")
    public ModelAndView goodList(){
        ModelAndView modelAndView=new ModelAndView();
        List<Good> goods=goodService.findAllGood();
        modelAndView.addObject("goods",goods);
        modelAndView.setViewName("navi");
        return modelAndView;
    }

    @RequestMapping("/userRegister")
    public String userRegister(User user){
        boolean r=userService.userRegister(user);
        if (r==true){
            return "success";
        }else {
            return "error";
        }
    }

    @RequestMapping("/userUpdate")
    public String userUpdate(User user){
        System.out.println(user);
        boolean r=userService.userUpdate(user);
        if (r==true){
            return "success";
        }else {
            return "error";
        }
    }

    @RequestMapping("/registerPage")
    public String registerPage(){
        return "register";
    }

    @RequestMapping("/loginPage")
    public String loginPage(){
        return "login";
    }

    @RequestMapping("/userUpdatePage")
    public ModelAndView userUpdatePage(User user){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("userUpdate");
        modelAndView.addObject("user",userService.findUserInfo(user));
        return modelAndView;
    }
}
